import React, { useEffect, useState } from "react";
import { Input, Button, Badge, Layout, Grid, message } from "antd";
import type { InputProps, ButtonProps, BadgeProps } from "antd";
import { 
  BrowserRouter as Router, 
  Routes, 
  Route, 
  useLocation,
  useNavigate,
  useParams,
  Navigate,
} from "react-router-dom";
import {
  SearchOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  AppstoreOutlined,
  HomeOutlined,
  BellOutlined,
} from "@ant-design/icons";
import HomePage from "./components/HomePage";
import CategoryPage from "./components/CategoryPage";
import CartPage from "./components/CartPage";
import ProfilePage from "./components/ProfilePage";
import { CartItem } from "./components/CartPage";
import ProductDetailPage from "./components/ProductDetailPage";
import CheckoutPage from "./components/CheckoutPage";
import PaymentPage from "./components/PaymentPage";
import OrderDetailPage from "./components/OrderDetailPage";
import AdminRoutes from "./admin/routes";
import { createOrder, updateOrderStatus } from "./services/mockOrderService";
import { OrderStatus } from './types/order';
import OrderListPage from './components/OrderListPage';
import LoginPage from "./components/LoginPage";
const { Header, Content, Footer } = Layout;
const { useBreakpoint } = Grid;

const MallHomePage: React.FC = () => {
  //底部导航栏
  const [activeTab, setActiveTab] = useState("home");
  const [searchQuery, setSearchQuery] = useState("");
  const screens = useBreakpoint();
  //读取选中的商品
  const [selectedProduct, setSelectedProduct] = useState<any>(null);
  const isMobile = !screens.md;
  const iconSize = isMobile ? 18 : 20;
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [cartCount, setCartCount] = useState(0);
  //订单列表，
  const [orders, setOrders] = useState<any[]>(() => {
    // 从 localStorage 恢复订单数据
    const savedOrders = localStorage.getItem('orders');
    return savedOrders ? JSON.parse(savedOrders) : [];
  });

  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState<any>(null);

  //登录成功会将状态存进去，然后在登录页面会读取状态，然后跳转到首页
  //登录成功后，会将用户信息存储在localStorage中，然后在页面加载时读取用户信息，然后跳转到首页
  const handleLogin = (userData: any) => {
    setIsLoggedIn(true);
    setUserInfo({
      ...userData,
      orders: orders  // 将订单数据添加到用户信息
    });
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('userInfo', JSON.stringify(userData));
    message.success("登录成功！");
  };

  const handleLogout = () => {
    setIsLoggedIn(false);
    setUserInfo(null);
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('userInfo');
    message.success("已退出登录");
    navigate('/login');
  };

  //恢复持久化的数据
  useEffect(() => {
    const storedLogin = localStorage.getItem('isLoggedIn');
    const storedUser = localStorage.getItem('userInfo');

    if (storedLogin === 'true' && storedUser) {
      setIsLoggedIn(true);
      const user = JSON.parse(storedUser);
      setUserInfo({
        ...user,
        orders: orders  // 恢复时也添加订单数据
      });
    }
  }, [orders]);  // 添加orders依赖，当订单更新时同步

  React.useEffect(() => {
    const path = location.pathname;
    if (path === '/') {
      setActiveTab('home');
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
    } else if (path === '/category') {
      setActiveTab('category');
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
    } else if (path === '/cart') {
      setActiveTab('cart');
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
    } else if (path === '/profile') {
      setActiveTab('profile');
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
    } else if (path.startsWith('/product/')) {
      const productId = path.split('/')[2];
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
    } else if (path === '/checkout') {
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'checkout'}));
    } else if (path === '/payment') {
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'payment'}));
    } else if (path.startsWith('/order/')) {
      const orderId = path.split('/')[2];
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'order'}));
      setSelectedOrderId(orderId);
    } else if (path === '/orders') {
      setSelectedProduct(null);
      setPurchaseFlow(prev => ({...prev, step: 'cart'}));
      setActiveTab('orderList');
    }
  }, [location]);

  //底部导航栏
  const navItems = [
    { key: "home", label: "首页", icon: <HomeOutlined style={{ fontSize: iconSize }} /> },
    { key: "category", label: "分类", icon: <AppstoreOutlined style={{ fontSize: iconSize }} /> },
    { 
      key: "cart", 
      label: "购物车", 
      icon: (
        <Badge 
          count={cartCount} 
          style={{ backgroundColor: "#ff4d4f" }}
        >
          <ShoppingCartOutlined style={{ fontSize: iconSize }} />
        </Badge>
      ) 
    },
    { key: "profile", label: "我的", icon: <UserOutlined style={{ fontSize: iconSize }} /> }
  ];
  
  const [purchaseFlow, setPurchaseFlow] = useState({
    step: 'cart',
    order: null as any,
    address: null as any,
    paymentMethod: 'wechat',
  });

  //确认订单界面
  const startCheckout = (items: any[]) => {
    setPurchaseFlow({
      step: 'checkout',
      order: {
        id: `ORDER${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        items: items.map(item => ({
          id: item.id,
          name: item.name,
          price: item.price,
          quantity: item.quantity,
          selectedColor: item.selectedColor,
          selectedStorage: item.selectedStorage,
          image: item.image
        })),
        totalAmount: items.reduce((total, item) => total + item.price * item.quantity, 0),
        createdAt: new Date().toISOString(),
        status: OrderStatus.PENDING
      },
      address: null,
      paymentMethod: ''
    });
    navigate('/checkout');
  };

  //商品单独结算
  const handleBuyNow = (product: any) => {
    startCheckout([product]);
  };

  //购物车结算
  const handleCartCheckout = () => {
    startCheckout(cartItems);
  };
//提交订单
  const submitOrder = async (address: any) => {
    const newOrder = await createOrder({
      items: purchaseFlow.order.items,
      totalAmount: purchaseFlow.order.totalAmount,
      status: OrderStatus.PENDING,
      address: address,
      userId: userInfo.id,
      paymentMethod: 'wechat'  // 在创建订单时就设置默认支付方式
    });

    setPurchaseFlow(prev => {
      const updatedFlow = {
        ...prev,
        step: 'payment',
        order: {
          ...newOrder,
          totalAmount: prev.order.totalAmount,
          address: address,
          paymentMethod: 'wechat'  // 确保前端状态也设置默认支付方式
        },
        address: address,
        paymentMethod: 'wechat'
      };
      navigate('/payment');
      return updatedFlow;
    });
    
    // 更新订单列表
    const formattedOrder = {
      ...newOrder,
      date: new Date().toLocaleDateString(),
      status: OrderStatus.PENDING,
      total: purchaseFlow.order.totalAmount,
      items: purchaseFlow.order.items,
      userId: userInfo.id,
      paymentMethod: 'wechat'  // 确保订单列表中也有支付方式
    };
    setOrders(prev => {
      const newOrders = [...prev, formattedOrder];
      // 保存到 localStorage
      localStorage.setItem('orders', JSON.stringify(newOrders));
      return newOrders;
    });
  };

  //完成支付
  const completePayment = async () => {
    if (!purchaseFlow.order) return;

    const updatedOrder = await updateOrderStatus(
      purchaseFlow.order.id, 
      OrderStatus.PAID,
      purchaseFlow.paymentMethod
    );
    
    setOrders(prev => {
      const newOrders = prev.map(order => 
        order.id === updatedOrder.id ? { 
          ...order, 
          status: OrderStatus.PAID,
          paymentMethod: purchaseFlow.paymentMethod  // 更新支付方式
        } : order
      );
      // 保存到 localStorage
      localStorage.setItem('orders', JSON.stringify(newOrders));
      return newOrders;
    });

    setPurchaseFlow(prev => {
      const updatedFlow = {
        ...prev,
        step: 'order',
        order: {
          ...prev.order,
          ...updatedOrder,
          status: OrderStatus.PAID,
          items: prev.order.items,
          address: prev.address || prev.order.address,
          paymentMethod: prev.paymentMethod,
          totalAmount: prev.order.totalAmount,
          createdAt: prev.order.createdAt
        }
      };
      navigate(`/order/${purchaseFlow.order.id}`);
      return updatedFlow;
    });

    clearCart();
  };

  const backToCart = () => {
    setPurchaseFlow({
      step: 'cart',
      order: null,
      address: null,
      paymentMethod: 'wechat'
    });
    navigate('/cart');
  };

  const backToHome = () => {
    setActiveTab('home');
    setPurchaseFlow({
      step: 'cart',
      order: null,
      address: null,
      paymentMethod: 'wechat'
    });
    navigate('/');
  };

  //支付切换
  const handlePaymentMethodChange = (method: string) => {
    setPurchaseFlow(prev => ({
      ...prev,
      paymentMethod: method
    }));
  };
//

  const addToCart = (product: any) => {
    setCartItems(prevItems => {
      const existingItem = prevItems.find(item => item.id === product.id);
      if (existingItem) {
        return prevItems.map(item => 
          item.id === product.id 
            ? {...item, quantity: item.quantity + 1} 
            : item
        );
      } else {
        return [...prevItems, {
          id: product.id,
          name: product.name,
          price: product.price,
          originalPrice: product.originalPrice,
          image: product.image,
          quantity: 1
        }];
      }
    });
    setCartCount(prev => prev + 1);
  };

  const updateQuantity = (id: number, quantity: number) => {
    if (quantity < 1) return;
    
    setCartItems(prevItems => 
      prevItems.map(item => 
        item.id === id ? {...item, quantity} : item
      )
    );
    
    const item = cartItems.find(item => item.id === id);
    if (item) {
      setCartCount(prev => prev - item.quantity + quantity);
    }
  };

  const removeFromCart = (id: number) => {
    setCartItems(prevItems => {
      const itemToRemove = prevItems.find(item => item.id === id);
      if (itemToRemove) {
        setCartCount(prev => prev - itemToRemove.quantity);
      }
      return prevItems.filter(item => item.id !== id);
    });
  };

  const clearCart = () => {
    setCartItems([]);
    setCartCount(0);
  };
  
  //界面的切换
  const handleNavigate = (tab: string) => {
    setActiveTab(tab);
    switch(tab) {
      case 'home':
        navigate('/');
        break;
      case 'category':
        navigate('/category');
        break;
      case 'cart':
        navigate('/cart');
        break;
      case 'profile':
        navigate('/profile');
        break;
      case 'orderList':
        navigate('/orders');
        break;
    }
  };

  const viewProductDetail = (product: any) => {
    setSelectedProduct(product);
    navigate(`/product/${product.id}`);
  };

  const viewOrderDetail = (orderId: string) => {
    setSelectedOrderId(orderId);
    navigate(`/order/${orderId}`);
  };

  const renderContent = () => {
    if (purchaseFlow.step === 'checkout') {
      return (
        <CheckoutPage 
          isMobile={isMobile} 
          order={purchaseFlow.order}
          onSubmit={submitOrder}
          onBack={backToCart}
        />
      );
    }
    if (activeTab === 'orderList') {
      return (
        <OrderListPage 
          isMobile={isMobile}
          orders={orders}
          onBack={() => setActiveTab('profile')}
          onViewOrder={(orderId) => {
            setSelectedOrderId(orderId);
            setActiveTab('orderDetail');
          }}
        />
      );
    }
    
    if (activeTab === 'orderDetail' && selectedOrderId) {
      const order = orders.find(o => o.id === selectedOrderId);
      if (order) {
        return (
          <OrderDetailPage 
            isMobile={isMobile}
            order={order}
            onBackToHome={backToHome}
            onBackToCart={() => setActiveTab('cart')}
            onBackToOrderList={() => {
              setActiveTab('orderList');
              setSelectedOrderId(null);
            }}
          />
        );
      }
    }
    
    if (purchaseFlow.step === 'order') {
      return (
        <OrderDetailPage 
          isMobile={isMobile} 
          order={purchaseFlow.order}
          onBackToHome={backToHome}
          onBackToCart={() => setPurchaseFlow(prev => ({...prev, step: 'cart'}))}
          onBackToOrderList={() => {
            setActiveTab('orderList');
            setPurchaseFlow(prev => ({ ...prev, step: 'cart' }));
          }}
        />
      );
    }
    if (purchaseFlow.step === 'payment') {
      return (
        <PaymentPage 
          isMobile={isMobile} 
          order={purchaseFlow.order}
          address={purchaseFlow.address}
          paymentMethod={purchaseFlow.paymentMethod}
          onPay={completePayment}
          onBack={() => setPurchaseFlow(prev => ({...prev, step: 'checkout'}))}
          onPaymentMethodChange={handlePaymentMethodChange}
        />
      );
    }
    
    if (selectedProduct) {
      return (
        <ProductDetailPage 
          isMobile={isMobile}
          product={selectedProduct}
          onBack={() => setSelectedProduct(null)}
          addToCart={addToCart}
          onBuyNow={handleBuyNow}
          setActiveTab={setActiveTab}
        />
      );
    }
    switch (activeTab) {
      case "home":
        return <HomePage isMobile={isMobile} addToCart={addToCart}  setSelectedProduct={setSelectedProduct} />;
      case "category":
        return <CategoryPage isMobile={isMobile} />;
      case "cart":
        return (
          <CartPage 
            isMobile={isMobile} 
            setActiveTab={setActiveTab} 
            cartItems={cartItems}
            updateQuantity={updateQuantity}
            removeFromCart={removeFromCart}
            clearCart={clearCart}
            onCheckout={handleCartCheckout}
          />
        );
        case "profile":
          return (
            <ProfilePage 
              isMobile={isMobile}
              orders={orders} 
              setActiveTab={handleNavigate}
              userInfo={userInfo}
              onLogout={handleLogout}
              isLoggedIn={isLoggedIn}
              onLogin={handleLogin}
              onViewOrderDetail={viewOrderDetail}
            />       
          );
      default:
        return <HomePage isMobile={isMobile} addToCart={addToCart} setSelectedProduct={setSelectedProduct} />;
    }
  };

  const shouldShowFooter = () => {
    return !selectedProduct && 
           purchaseFlow.step === 'cart' && 
           location.pathname !== '/login' &&
           location.pathname !== '/checkout' &&
           location.pathname !== '/payment' &&
           !location.pathname.startsWith('/order/') &&
           location.pathname !== '/orders';
  };

  return (
    <Layout style={{ 
      minHeight: "100vh",
      height: "100vh",
      backgroundColor: "#f5f5f5",
      overflow: "hidden"
    }}>
      {location.pathname !== '/login' && (
        <Header style={{ 
          position: "fixed", 
          zIndex: 100, 
          width: "100%", 
          padding: "0 10px", 
          background: "#fff", 
          height: isMobile ? 48 : 54,
          boxShadow: "0 1px 4px rgba(0, 0, 0, 0.1)"
        }}>
          <div style={{ display: "flex", alignItems: "center", height: "100%" }}>
            <div style={{ flex: 1 }}>
              <Input
                placeholder="搜索商品"
                prefix={<SearchOutlined style={{ color: "#bfbfbf" }} />}
                value={searchQuery}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchQuery(e.target.value)}
                style={{ 
                  borderRadius: 18,
                  height: isMobile ? 34 : 38
                }}
              />
            </div>
            <Button 
              type="text" 
              icon={<BellOutlined style={{ fontSize: iconSize }} />} 
              style={{ marginLeft: 8, width: 40 }} 
            />
          </div>
        </Header>
      )}

      <Content style={{ 
        paddingTop: location.pathname === '/login' ? 0 : (isMobile ? 48 : 54),
        paddingBottom: isMobile ? 56 : 60,
        height: location.pathname === '/login' ? '100vh' : `calc(100vh - ${isMobile ? 104 : 114}px)`,
        overflowY: "auto",
        maxWidth: "100%",
        margin: 0,
        width: "100%"
      }}>
        <Routes>
        <Route path="/" element={
          isLoggedIn ? 
            <HomePage isMobile={isMobile} addToCart={addToCart} setSelectedProduct={viewProductDetail} /> 
            : 
            <LoginPage isMobile={isMobile} onLogin={handleLogin} />
        } />
          <Route path="/category" element={<CategoryPage isMobile={isMobile} />} />
          <Route path="/cart" element={
            isLoggedIn ? (
            <CartPage 
              isMobile={isMobile} 
              setActiveTab={handleNavigate}
              cartItems={cartItems}
              updateQuantity={updateQuantity}
              removeFromCart={removeFromCart}
              clearCart={clearCart}
              onCheckout={handleCartCheckout}
            />
            ):(
              <Navigate to="/login" state={{ from: location }} replace/> 
            )
          } />
         <Route path="/login" element={
          !isLoggedIn ? 
            <LoginPage isMobile={isMobile} onLogin={handleLogin} /> 
            : 
            <Navigate to="/" replace />
        } />
         <Route path="/profile" element={
            <ProfilePage 
              isMobile={isMobile}
              orders={orders}
              setActiveTab={handleNavigate}
              userInfo={userInfo}
              onLogout={handleLogout}
              isLoggedIn={isLoggedIn}
              onLogin={handleLogin}
              onViewOrderDetail={viewOrderDetail}
            />
          } />
          <Route path="/product/:id" element={
            <ProductDetailPage 
              isMobile={isMobile}
              product={selectedProduct}
              onBack={() => navigate(-1)}
              addToCart={addToCart}
              onBuyNow={handleBuyNow}
              setActiveTab={handleNavigate}
            />
          } />
          <Route path="/checkout" element={
            <CheckoutPage 
              isMobile={isMobile} 
              order={purchaseFlow.order}
              onSubmit={submitOrder}
              onBack={backToCart}
            />
          } />
          <Route path="/payment" element={
            <PaymentPage 
              isMobile={isMobile} 
              order={purchaseFlow.order}
              address={purchaseFlow.address}
              paymentMethod={purchaseFlow.paymentMethod}
              onPay={completePayment}
              onBack={() => navigate('/checkout')}
              onPaymentMethodChange={handlePaymentMethodChange}
            />
          } />
          <Route path="/order/:id" element={
            <OrderDetailPage 
              isMobile={isMobile}
              order={purchaseFlow.order || orders.find(o => o.id === selectedOrderId)}
              onBackToHome={backToHome}
              onBackToCart={() => navigate('/cart')}
              onBackToOrderList={() => navigate('/orders')}
            />
          } />
          <Route path="/orders" element={
            <OrderListPage 
              isMobile={isMobile}
              orders={orders}
              onBack={() => navigate('/profile')}
              onViewOrder={viewOrderDetail}
            />
          } />
        </Routes>
      </Content>

      {shouldShowFooter() && (
        <Footer
          style={{
            position: "fixed",
            bottom: 0,
            zIndex: 100,
            width: "100%",
            background: "#fff",
            padding: "6px 0",
            height: isMobile ? 56 : 60,
            borderTop: "1px solid #f0f0f0",
            boxShadow: "0 -1px 4px rgba(0, 0, 0, 0.05)",
            maxWidth: "100%",
            margin: 0,
            left: 0,
            transform: "none"
          }}
        >
          <div style={{ display: "flex", justifyContent: "space-around" }}>
            {navItems.map((item) => (
              <div
                key={item.key}
                onClick={() => handleNavigate(item.key)}
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  padding: "0 6px",
                  cursor: "pointer",
                  color: activeTab === item.key ? "#1890ff" : "#666",
                  minWidth: isMobile ? 60 : 70
                }}
              >
                <div>{item.icon}</div>
                <div style={{ fontSize: isMobile ? 11 : 12, marginTop: 2 }}>{item.label}</div>
              </div>
            ))}
          </div>
        </Footer>
      )}
    </Layout>
  );
};

const AppRoutes: React.FC = () => {
  const location = useLocation();
  const isAdminRoute = location.pathname.startsWith('/admin');

  if (isAdminRoute) {
    return <AdminRoutes />;
  }

  return <MallHomePage />;
};

const App: React.FC = () => {
  return (
    <Router>
      <AppRoutes />
    </Router>
  );
};

export default App;